// AAA.cpp: implementation of the AAA class.
// Download by http://www.codefans.net
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "TestForNetInfo.h"
#include "AAA.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
#include <winsock.h>
#include <stdio.h>
AAA::AAA()
{
	
}

AAA::~AAA()
{
	
}

CString AAA::GetRIP()
{
	CString csRes = "error";
	WSAData wsaDat;
	short int Port = 80;
	WSAStartup(MAKEWORD(1,1),&wsaDat);
	SOCKET sd = socket(AF_INET, SOCK_STREAM, 0);
	SOCKADDR_IN sockAddr;
	memset((void*)&sockAddr,0,sizeof(sockAddr));
	sockAddr.sin_family=AF_INET;
	sockAddr.sin_port=htons(Port);
	sockAddr.sin_addr.s_addr=inet_addr("121.14.117.131");
	connect(sd,(LPSOCKADDR)&sockAddr,sizeof(sockAddr));
	char sendstr[]="GET /ip2city.asp HTTP/1.1\r\nAccept: */*\r\nReferer: ******\r\nUser-Agent: Mozilla/4.0\r\nHost: www.ip138.com\r\nConnection: close\r\n\r\n\0";
	char* p;
	int iLen = strlen(sendstr);
	p = sendstr;
	while (iLen){
		int iRet = send(sd,p,iLen,0);
		if (iRet > 0) {
			p += iRet;
			iLen -= iRet;
			continue;
		}
		return csRes;
	}
	char recvstr[1024];
	memset(recvstr,0,1024);
	p = recvstr;
	char* iIndex_Head ;
	iLen = 1024;
	int need_len = -1;
	while (iLen){
		int iRet = recv(sd,p,iLen,0);
		if (iRet <= 0) {
			return csRes;
		}
		p += iRet;
		iLen -= iRet;
		if ((iIndex_Head = strstr(recvstr,"\r\n\r\n"))&&(need_len==-1)) {
			char* iIndex = strstr(recvstr,"Content-Length:");
			if (!iIndex) {
				continue;
			}
			char *p1 =  iIndex + strlen("Content-Length:");
			need_len = iIndex_Head - recvstr + 2 + atol(p1);
			
		}
		if (1024 - iLen >=need_len) { break;
        
		}
	}
	char *p1 = strstr(iIndex_Head,"[");
	char *p0 = strstr(p1,"]");
	*p0 = '\0';
	printf("IP=%s",p1+1);
	closesocket(sd);
	WSACleanup();
	csRes = &(p1[1]);
	return csRes;
}
